
package com.mephi.util.filter;


import java.io.File;
import java.util.Collections;
import java.util.List;
import com.mephi.util.Constants;


/**
 * Filters for xml files. It checks if files have extensions given in the list
 *  for constructor. The alowable elements are for example <i>[".xml",".txt"]</i>.
 * 
 * @author mephisto
 * 2011-07-17
 */
public class FileFilter extends javax.swing.filechooser.FileFilter
{
	public FileFilter(List<String> extensionList)
	{
		this.extensionList = extensionList;
		Collections.sort(extensionList);
	}
	
	@Override
	public boolean accept(File f)
	{
		return f.isDirectory() || contains(f.getName().toLowerCase());
	}

	@Override
	public String getDescription()
	{
		StringBuilder sB = new StringBuilder();
		for(int i = 0, size = extensionList.size(); i < size; i++)
		{
			if (i != size-1)
				sB.append(extensionList.get(i)).append(", ");
			else
				sB.append(extensionList.get(i)).append(" files");
		}
		return sB.toString();
	}
	
	private boolean contains(String path)
	{
		int dotPos = path.lastIndexOf(Constants.DOT_STRING);
		if (dotPos < 0)
			return false;
		String extension = path.substring(dotPos+1);
		return extensionList.contains(extension);
	}
	
	
	private List<String> extensionList; 
}
